package se.com.movie.reader.writer;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import se.com.movie.reader.model.Movie;
import se.com.movie.reader.xml.XmlUtil;

public class XMLWriter {
	public static Element mRoot = null;
	public static Document mDocument = null;

	public static void open() {
		try {
			mDocument = XmlUtil.createDocument("1.0", "UTF-16");
			mRoot = XmlUtil.createRoot(mDocument, "movies");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void write(Movie movie) {
		Element movieElement = XmlUtil.addElement(mRoot, "movie");
		Element name = XmlUtil.addElement(movieElement, "name");
		Element path = XmlUtil.addElement(movieElement, "path");
		name.setTextContent(movie.getMovie());
		path.setTextContent(movie.getPath());
	}

	public static void close() {
		try {
			XmlUtil.createFile(mDocument, "movies.xml");
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
}
